import React, { useState } from 'react';
import moment from 'moment';
import { Button, Form, Input, message, Modal, Select } from 'antd';
import { HttpCode } from '#/utils/contacts.js';
import { TRCheckboxModal } from '@/components/index.js';
import TRNotification from '#/utils/notification.js';
import planIcon from '@/assets/img/plan_icon.png';
import { batchSavePendingRelaH } from '../../service';
import {
  BATCH_TODO_CONTENT_TYPE,
  PENDING_TIME_TYPE,
  STATION_LIST_TYPE,
  TYPE_LIST,
} from '../../dictionary';
import type { ISearchFormData } from '../../type';
import { PendingTime } from '../index';
import styles from './index.less';

const TextArea = Input.TextArea;
interface IProps {
  onPress: (data: Record<string, any>) => void;
  /**
   * searchFormData
   */
  searchFormData: ISearchFormData;
  /**
   * 批量创建对象
   */
  value?: any;
  /**
   * 刷新key值
   */
  setFlashKey: (e: number) => void;
  setMonthflashKey: (e: number) => void;
}

const CreateBatchTodoForNSComponent = (props: IProps) => {
  const { onPress, searchFormData, value = [], setFlashKey, setMonthflashKey } = props;
  const [visible, setVisible] = useState<boolean>(true);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [transactionType, setTransactionType] = useState<number>(1);
  const [stationListType, setStationListType] = useState<number>(1);
  const { dealElementOptions, dealElementModalOptions, dealElementDataObj } = searchFormData;

  const initialValues = {
    transactionType: 1,
    stationListType: 1,
  };
  const [form] = Form.useForm();

  // 取消按钮
  const _onCancel = () => {
    setVisible(false);
    onPress({ index: 0 });
  };

  // 点击交易单元弹出Modal框
  const handelSelectDealElement = async () => {
    let data = form.getFieldsValue()?.stationList || [];
    data = data.map((item: any) => dealElementDataObj[item]?.[0]?.value);
    const result = await TRCheckboxModal.show({
      treeData: dealElementModalOptions,
      value: data,
      title: '交易单元',
    });
    if (result.index === 1) {
      const checkedKeys = result?.checkedKeys?.map(
        (item: any) => dealElementDataObj?.[item]?.[0]?.value,
      );
      form.setFieldsValue({ stationList: checkedKeys });
    }
  };

  // 表单提交
  const onSubmit = () => {
    form &&
      form.validateFields().then(async (values) => {
        setIsLoading(true);
        const { pending = {}, calendarDate, ...rest } = values;
        const pendingStartTime = moment(pending?.pendingStartTime).format('HH:mm:ss');
        const pendingEndTime = moment(pending?.pendingEndTime).format('HH:mm:ss');
        const params = value
          ? value.map((item: any) => {
              const { declarationStartTime, declarationEndTime, ...restOther } = item;
              return {
                ...restOther,
                ...rest,
                pendingStartTime:
                  pending?.pendingTimeType === 1 &&
                  (item?.relaType === TYPE_LIST.CUSTOM_SEQUENCE ||
                    item?.relaType === TYPE_LIST.SYSTEM_SEQUENCE)
                    ? moment(item?.declarationStartTime).format('HH:mm:ss')
                    : pendingStartTime,
                pendingEndTime:
                  pending?.pendingTimeType === 1 &&
                  (item?.relaType === TYPE_LIST.CUSTOM_SEQUENCE ||
                    item?.relaType === TYPE_LIST.SYSTEM_SEQUENCE)
                    ? moment(item?.declarationEndTime).format('HH:mm:ss')
                    : pendingEndTime,
              };
            })
          : {};

        const res: any = await batchSavePendingRelaH(params);
        if (res?.statusCode === HttpCode.SUCCESS) {
          setFlashKey(moment().valueOf());
          setMonthflashKey(moment().valueOf());
          _onCancel();
          message.info('创建成功！');
        } else {
          message.info(res?.message || '创建失败！');
        }
        setIsLoading(false);
      });
  };

  return (
    <Modal
      className={styles.modal}
      centered
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} />
          <span className={styles.title}>批量创建</span>
        </div>
      }
      onCancel={_onCancel}
      footer={null}
    >
      <div className={styles.container}>
        <Form
          className={styles.form}
          form={form}
          name="createBatchTodo"
          initialValues={initialValues}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          colon={false}
          labelAlign="left"
          autoComplete="off"
          requiredMark={false}
        >
          <Form.Item
            name="transactionType"
            label="待办内容"
            rules={[{ required: true, message: '请选择' }]}
          >
            <Select
              options={BATCH_TODO_CONTENT_TYPE}
              onChange={(e: number) => setTransactionType(e)}
            />
          </Form.Item>
          {transactionType === 2 && (
            <Form.Item
              name="transactionArrange"
              label=" "
              rules={[
                { required: true, message: '请填写待办内容' },
                { max: 50, message: '待办内容不可超过50个字符' },
              ]}
            >
              <TextArea maxLength={50} placeholder="请填写待办内容" />
            </Form.Item>
          )}
          <Form.Item label="待办日期">引用公告/序列日期</Form.Item>
          <Form.Item
            name="pending"
            label="待办时间"
            rules={[{ required: true, message: '请选择待办时间' }]}
          >
            <PendingTime options={PENDING_TIME_TYPE} />
          </Form.Item>
          <Form.Item
            name="stationListType"
            label="交易单元"
            rules={[{ required: true, message: '请选择' }]}
          >
            <Select options={STATION_LIST_TYPE} onChange={(e: number) => setStationListType(e)} />
          </Form.Item>
          {stationListType === 2 && (
            <Form.Item
              name="stationList"
              label=" "
              rules={[{ required: true, message: '请选择交易单元' }]}
            >
              <Select
                placeholder={'交易单元'}
                showArrow={true}
                open={false}
                onClick={handelSelectDealElement}
                mode="multiple"
                maxTagTextLength={1}
                maxTagCount={1}
                options={dealElementOptions as any[]}
              />
            </Form.Item>
          )}
        </Form>
        <Button type="primary" className={styles.submitBtn} loading={isLoading} onClick={onSubmit}>
          提交
        </Button>
      </div>
    </Modal>
  );
};

class CreateBatchTodoForNSModal {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <CreateBatchTodoForNSComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new CreateBatchTodoForNSModal();
